import { messages, deepFullCopy } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Form, Input, Switch, Select, Row, Col, Radio, Affix, Button, message, Modal, Popover, Icon } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;

import Chooser from 'components/chooser'
import chooserData from 'share/chooserData'
import LanguageInput from 'components/template/language-input/language-input'
import Condition from 'components/condition'
const { If } = Condition;
import ruleOptions from 'containers/expense-reimbursement-control/expense-standard/reimbursement/rule-options.data'
import 'styles/expense-reimbursement-control/reimbursement/new-rule.scss'
import reimburseService from 'containers/expense-reimbursement-control/expense-standard/reimbursement/reimbursement.service'
import summaryCheckInfoEn from 'images/expense/summary-check-info-en.png'
import errorMessage from 'share/errorMessage'

class NewRule extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      submitLoading: false,
      ruleOptions: deepFullCopy(ruleOptions),
      participantsIsEnable: false, //费用参与人标准
      info: {}, //规则详情
      i18n: {},
    }
  }

  componentDidMount() {
    this.modifyRuleOptions()
  }

  componentWillReceiveProps(nextProps) {
    let sourceInfo = deepFullCopy(nextProps.params.info || {});
    if (sourceInfo.ruleOID && sourceInfo.ruleOID !== this.state.info.ruleOID) {
      this.setState({
        info: sourceInfo,
        participantsIsEnable: sourceInfo.participantsEnable
      }, () => {
        this.modifyRuleOptions()
      })
    }
  }

  //初始化表单显示项
  modifyRuleOptions = () => {
    const { tenantMode, company, params, language } = this.props;
    let { info, ruleOptions } = this.state;
    if (info.ruleOID) {
      ruleOptions.splice(0, 0, {
        id: 'code',
        label: messages('expense-reimbursement-control.key18')/*规则编码*/,
        type: 'input',
        disabled: true,
        initialValue: params.info.code,
        rules: [{
          required: true
        }]
      })
    }
    ruleOptions.map((item, index) => {
      if (item.id === 'expenseTypes') { //费用类型
        let chooserItem = deepFullCopy(chooserData['selectInvoiceType']);
        chooserItem.key = 'expenseTypeOID';
        item.chooserItem = chooserItem;
        item.listExtraParams = {
          enabled: true,
          subsidyType: 0,
          setOfBooksId: params.setOfBooksId
        }
      }
      if (item.id === 'forms') { //适用单据
        item.listExtraParams = {formTypeList: [3001, 3002, 3003]};
        tenantMode && (item.listExtraParams.setOfBooksId = params.setOfBooksId);
        !tenantMode && (item.listExtraParams.companyOID = company.companyOID)
      }
      if (item.id === 'companys') { //适用公司
        if (!tenantMode) { //公司模式下
          item.disabled = true;
          item.initialValue = [{name: company.name, companyOID: company.companyOID}];
        } else {
          let chooserItem = deepFullCopy(chooserData['available_company_setOfBooks']);
          chooserItem.key = 'companyOID';
          item.chooserItem = chooserItem;
          item.disabled = false;
          item.initialValue = undefined;
          item.listExtraParams.setOfBooksId = params.setOfBooksId;
        }
      }
      if (item.id === 'controlType') { //控制方式
        if (language.code === 'en') {
          item.label = (
            <span> {messages('expense-reimbursement-control.key33')/*控制方式*/}
              <Popover content={<img src={summaryCheckInfoEn} style={{width: 800}}/>}
                       overlayStyle={{maxWidth: 832}}>
                <Icon type="info-circle" className='default-color-font' style={{cursor: 'pointer', marginLeft: 5}} />
              </Popover>
            </span>
          )
        }
        if (info.controlType === 'SUMMARY') { //汇总校验
          this.handleSelectChange('controlType', 'SUMMARY', index);
        }
      }
      if (item.id === 'userGroups') { //适用人员
        let chooserItem = deepFullCopy(chooserData['user_group']);
        chooserItem.key = 'userGroupOID';
        item.chooserItem = chooserItem
      }
    });
    this.setState({ ruleOptions }, () => {
      if (info.participantsEnable) {
        ruleOptions.map((item, index) => {
          item.id === 'participantsEnable' && this.handleParticipantStandardChange(true, index)
        })
      }
    })
  };

  renderFormItem = (type, item, index) => {
    const { getFieldDecorator } = this.props.form;
    const { participantsIsEnable, i18n, info } = this.state;
    switch(type) {
      case 'input':
        return <Input disabled={item.disabled} placeholder={item.placeholder}/>;
      case 'languageInput':
        let i18nName = i18n[item.id] || (info.i18n ? (info.i18n[item.id] || []) : []);
        return (
          <LanguageInput
            isEdit
            inpRule={this.getInpRule(item.length)}
            placeholder={item.placeholder}
            name={info[item.id]}
            i18nName={i18nName}
            textArea={item.textArea}
            nameChange={(value, i18n) => this.handleI18nChange(value, i18n, item.id)}
          />
        );
      case 'switch':
        if (item.id === 'participantsEnable') { //费用参与人标准
          let standardOption = {
            id: 'participantsMode',
            options: [{
              value: 'HIGH',
              title: messages('expense-reimbursement-control.key19')/*就高*/,
              description: messages('expense-reimbursement-control.key20')/*费用归属人和参与人中的最高标准*/,
            },{
              value: 'SUM',
              title: messages('expense-reimbursement-control.key21')/*和值*/,
              description: messages('expense-reimbursement-control.key22')/*费用归属人和参与人的标准相加*/,
            }]
          };
          return (
            <Row>
              <Col span={4}>
                <Switch checked={participantsIsEnable}
                        onChange={value => this.handleParticipantStandardChange(value, index)}/>
              </Col>
              <If value={participantsIsEnable}>
                <Col span={20}>
                  <FormItem key="participantsMode">
                    {getFieldDecorator("participantsMode", {
                      rules: [{
                        required: true,
                        message: messages('common.please.select'/*请选择*/)
                      }],
                      initialValue: info.participantsMode || "HIGH"
                    })(
                      this.renderFormItem('select', standardOption)
                    )}
                  </FormItem>
                </Col>
              </If>
            </Row>
          )
        }
        return <Switch disabled={item.disabled}/>;
      case 'chooser':
        return <Chooser type={item.chooserType}
                        selectorItem={item.chooserItem}
                        valueKey={item.valueKey}
                        labelKey={item.labelKey}
                        listExtraParams={item.listExtraParams}
                        disabled={item.disabled}
                        placeholder={item.placeholder}/>;
      case 'select':
        return (
          <Select optionLabelProp="title"
                  disabled={item.disabled}
                  getPopupContainer={() => document.getElementsByClassName('new-rule')[0]}
                  onChange={value => this.handleSelectChange(item.id, value, index)}>
            {item.options.map(optionItem => (
              <Option key={optionItem.value} title={optionItem.title} className="new-rule-select-option">
                <div>
                  <div>{optionItem.title}</div>
                  <div className="description">{optionItem.description}</div>
                </div>
              </Option>
            ))}
          </Select>
        );
      case 'radio':
        return (
          <RadioGroup>
            {item.options.map(optionItem => (
              <Radio key={optionItem.value} value={optionItem.value}>{optionItem.title}</Radio>
            ))}
          </RadioGroup>
        )
    }
  };

  //修改多语言值
  handleI18nChange = (value, i18nValue, id) => {
    let {i18n} = this.state;
    i18n[id] = i18nValue;
    this.setState({i18n})
  };

  //获取多语言输入框的字符长度
  getInpRule = (num) => {
    let inpRule = [];
    this.props.languageList.map(language => {
      inpRule.push({
        length: num,
        language: language.code.toLowerCase()
      });
    });
    return inpRule;
  };

  //修改下拉框选择值
  handleSelectChange = (id, value, index) => {
    let { ruleOptions } = this.state;
    if (id === 'controlType') { //控制方式
      if (value === 'SUMMARY') { //汇总校验
        let standardItem =  {
          id: 'participantsEnable',
          label: messages('expense-reimbursement-control.key23')/*费用参与人标准*/,
          type: 'switch',
          rules: []
        };
        ruleOptions.splice(index + 1, 0, standardItem)
      } else {
        for (let i = 0; i < ruleOptions.length; i++ ) {
          if (~['participantsEnable', 'nonParticipants'].indexOf(ruleOptions[i].id)) {
            ruleOptions.splice(i, 1);
            i--
          }
        }
      }
      this.setState({ ruleOptions, participantsIsEnable: false })
    }
  };

  //修改费用参与人标准
  handleParticipantStandardChange = (value, index) => {
    let { ruleOptions } = this.state;
    let chooserItem = deepFullCopy(chooserData['user_group']);
    chooserItem.key = 'userGroupOID';
    let notTogetherItem = {
      id: 'nonParticipants',
      label: messages('expense-reimbursement-control.key24')/*不参与同住管控的人员*/,
      type: 'chooser',
      placeholder: messages('expense-reimbursement-control.key25')/*不填写则默认全部参与同住管控*/,
      chooserType: 'user_group',
      chooserItem,
      valueKey: 'userGroupOID',
      labelKey: 'name',
      listExtraParams: {},
      rules: []
    };
    if (value) {
      ruleOptions.splice(index + 1, 0, notTogetherItem)
    } else {
      ruleOptions.map((item, optionIndex) => {
        if (item.id === 'nonParticipants') { //不参与同住管控的人员
          ruleOptions.splice(optionIndex, 1)
        }
      })
    }
    this.setState({ ruleOptions, participantsIsEnable: value })
  };

  //保存
  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { params } = this.props;
        const { i18n, participantsIsEnable, info } = this.state;
        values.i18n = i18n;
        values.type = 'AMOUNT';
        values.participantsEnable = participantsIsEnable;
        values.businessType = 1001;
        info.ruleOID && (values.ruleOID = info.ruleOID);
        this.setState({ submitLoading: true });
        reimburseService.newOrEditRule(values, params.setOfBooksId).then(res => {
          if (res.data && res.data.errorCode === 'EXPENSE_STANDARD_0009') { //配置了拆单
            this.setState({ submitLoading: false });
            this.renderConfirmModal(e);
            return
          }
          if (info.ruleOID) {
            if (info.controlType === 'SUMMARY' && values.controlType !== 'SUMMARY') {
              reimburseService.updateControlInfo(info.ruleOID, []).then(() => {
                this.setState({ submitLoading: false });
                message.success(messages('common.save.success', {name: ""})/*保存成功*/);
                this.props.close('ruleAndControl')
              }).catch(e =>{
                errorMessage(e.response);
                this.setState({ submitLoading: false })
              })
            } else {
              this.setState({ submitLoading: false });
              message.success(messages('common.save.success', {name: ""})/*保存成功*/);
              this.props.close('rule')
            }
          } else {
            let ruleDetailUrl = menuRoute.getRouteItem('reimbursement-rule-detail').url;
            this.context.router.replace(ruleDetailUrl.replace(':setOfBooksId', params.setOfBooksId).replace(':ruleOID', res.data));
            message.success(messages('common.save.success', {name: ""})/*保存成功*/);
          }
        }).catch(e => {
          errorMessage(e.response);
          this.setState({ submitLoading: false })
        })
      }
    })
  };

  onCancel = () => {
    const {info} = this.state;
    if (info.ruleOID) {
      this.props.close()
    } else {
      let listUrl = menuRoute.getRouteItem('expense-standard').url;
      this.context.router.push(listUrl)
    }
  };

  //获取表单初始值
  getInitialValue = (id, initialValue) => {
    const { info } = this.state;
    let value = info[id] || initialValue;
    if (id === 'complianceCheck' || id === 'status') {
      typeof info[id] === 'boolean' && (value = info[id])
    }
    return value
  };

  //渲染拆单确认框
  renderConfirmModal = (e) => {
    return (
      Modal.confirm({
        title: messages('expense-reimbursement-control.key67')/*配置拆单则无法使用报销标准，是否去掉拆单？*/,
        content: (
          <div>
            <Row style={{color: '#f5222d'}}>{messages('expense-reimbursement-control.key68')/*去掉拆单，报销单将不按照费用类型拆单。*/}</Row>
            <Row>{messages('expense-reimbursement-control.key69')/*你还要继续吗？*/}</Row>
          </div>
        ),
        okText: messages('expense-reimbursement-control.key70')/*继续*/,
        width: 450,
        iconType: 'exclamation-circle',
        onOk: () => this.handleCancelSplitProfile(e)
      })
    )
  };

  //取消拆单配置
  handleCancelSplitProfile = (e) => {
    this.setState({ submitLoading: true });
    reimburseService.cancelSplitProfile().then(() => {
      this.handleSave(e)
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ submitLoading: false })
    })
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { submitLoading, ruleOptions, info } = this.state;
    const formItemLayout = {
      labelCol: { span: info.ruleOID ? 8 : 6 },
      wrapperCol: { span: info.ruleOID ? 12 : 10, offset: 1 },
    };
    return (
      <div className="new-rule">
        <Form onSubmit={this.handleSave} >
          {ruleOptions.map((item, index) => (
            <FormItem {...formItemLayout} label={item.label} key={item.id}>
              {getFieldDecorator(item.id, {
                rules: item.rules,
                valuePropName: item.type === 'switch' ? 'checked' : 'value',
                initialValue: this.getInitialValue(item.id, item.initialValue)
              })(
                this.renderFormItem(item.type, item, index)
              )}
            </FormItem>
          ))}
          <Affix offsetBottom={0} className={info.ruleOID ? 'slide-footer' : 'bottom-bar'}>
            <Button type="primary" htmlType="submit" loading={submitLoading}>
              {info.ruleOID ? messages('common.save'/*保存*/) : messages('expense-reimbursement-control.key26')/*创建*/}
            </Button>
            <Button onClick={this.onCancel} className="btn-cancel">
              {messages('common.cancel')/*取消*/}
            </Button>
          </Affix>
        </Form>
      </div>
    )
  }
}

NewRule.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode,
    languageList: state.login.languageList,
    language: state.main.language
  }
}

const WrappedNewRule = Form.create()(NewRule);

export default connect(mapStateToProps)(WrappedNewRule)
